<template>
  <div>
    <n-card>
      <template #header>
        <div class="header-container">
          <span class="header-title">图片生成</span>
          <div class="header-controls">
            <div class="model-selector-wrapper">
              <model-selector @select-model="handleModelSelect" :current-model="currentModel" direction="bottom" model-tag="生图" />
            </div>
          </div>
        </div>
      </template>
      
      <!-- 底部区域 - 左右结构 -->
      <div class="bottom-content">
        <!-- 左侧：滑块参数和文本域 -->
        <div class="slider-panel">
          <!-- 生成数量 -->
          <div class="control-item">
            <label class="control-label">生成数量</label>
            <n-slider
              v-model:value="generationCount"
              :min="1"
              :max="4"
              :step="1"
              show-tooltip
              :format-tooltip="(value) => `${value}张`"
            />
            <div class="slider-value">{{ generationCount }}张</div>
          </div>

          <!-- 图片宽度 -->
          <div class="control-item">
            <label class="control-label">图片宽度</label>
            <n-input-number
              v-model:value="imageWidth"
              :min="256"
              :max="2048"
              :step="64"
              placeholder="输入图片宽度"
            />
          </div>

          <!-- 图片高度 -->
          <div class="control-item">
            <label class="control-label">图片高度</label>
            <n-input-number
              v-model:value="imageHeight"
              :min="256"
              :max="2048"
              :step="64"
              placeholder="输入图片高度"
            />
          </div>

          <!-- 提示词权重 -->
          <div class="control-item">
            <label class="control-label">提示词权重</label>
            <n-slider
              v-model:value="weight"
              :min="1"
              :max="20"
              :step="0.1"
              show-tooltip
              :format-tooltip="(value) => `${value}`"
            />
            <div class="slider-value">{{ weight }}</div>
          </div>

          <!-- 提示词 -->
          <div class="control-item">
            <label class="control-label">提示词</label>
            <n-input
              v-model:value="message"
              type="textarea"
              placeholder="输入提示词"
              :autosize="{ minRows: 3, maxRows: 5 }"
              style="width: 100%;"
            />
          </div>



          <!-- 生成按钮 -->
          <div class="control-item generate-button-container">
            <n-button type="primary" @click="handleGenerateImage" size="large" style="width: 100%;" :loading="isGenerating">生成</n-button>
          </div>
        </div>

        <!-- 右侧：图片区域 -->
        <div class="image-panel">
          <!-- 主要预览图 -->
          <div class="main-preview">
            <n-image
              v-if="activeImageUrl"
              :src="activeImageUrl"
              alt="生成的图片"
              class="preview-image"
              :preview-disabled="false"
              show-toolbar
            />
            <div v-else class="placeholder-image">
              <n-icon size="48" color="#aaa">
                <ImageOutline />
              </n-icon>
              <p>图片将在这里显示</p>
            </div>
          </div>

          <!-- 历史记录 -->
          <div class="history-container">
            <button 
              v-if="showLeftArrow" 
              class="arrow-button arrow-left"
              @click="scrollToLeft"
              :class="{ 'arrow-visible': showLeftArrow }"
            >
              <n-icon size="16">
                <CaretBackOutline />
              </n-icon>
            </button>
            
            <div class="history-scroll-wrapper" ref="historyScrollRef">
              <transition-group name="history-item" tag="div" class="history-grid">
                <div 
                  v-for="(image, index) in generatedImages" 
                  :key="image.url + index" 
                  class="history-item" 
                  @click="showImage(index)"
                >
                  <img
                    :src="image.url"
                    :alt="image.name || `历史图片 ${index+1}`"
                    class="history-image"
                    :class="{ 'active-history': index === activeImageIndex }"
                  />
                </div>
              </transition-group>
            </div>

            <button 
              v-if="showRightArrow" 
              class="arrow-button arrow-right"
              @click="scrollToRight"
              :class="{ 'arrow-visible': showRightArrow }"
            >
              <n-icon size="16">
                <CaretForwardOutline />
              </n-icon>
            </button>
          </div>
        </div>
      </div>
    </n-card>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, nextTick, onMounted, onUnmounted, watch } from 'vue';
import { NButton, NInputNumber, NInput, NSlider, NIcon, NCard, NImage } from 'naive-ui';
import { ImageOutline, CaretBackOutline, CaretForwardOutline } from '@vicons/ionicons5';
import ModelSelector from '../../chat/components/ModelSelector.vue';
import { useModelStore } from '../../shared/stores/model';
import { apiConfig } from '../../shared/services/api-config';

const modelStore = useModelStore();

// 处理模型选择
const handleModelSelect = (model: number) => {
  currentModel.value = model;
  // 更新modelStore中的currentImageModel
  modelStore.setCurrentImageModel(model);
};

// 状态变量
const currentModel = computed({
  get: () => modelStore.currentImageModel,
  set: (val: number) => {
    modelStore.setCurrentImageModel(val);
  }
});
const isGenerating = ref(false);
const generationCount = ref(1);
const imageWidth = ref(512);
const imageHeight = ref(512);
const weight = ref(7.5);
const message = ref('Q版火影忍者人物手办');
const generatedImages = ref([
  { url: 'https://picsum.photos/255/255?random=1', name: '示例图片1' },
  { url: 'https://picsum.photos/255/255?random=2', name: '示例图片2' },
  { url: 'https://picsum.photos/255/255?random=3', name: '示例图片3' }
]);
const activeImageIndex = ref(0);
const activeImageUrl = computed(() => generatedImages.value.length > 0 ? generatedImages.value[activeImageIndex.value].url : null);

// 历史记录滚动相关
const historyScrollRef = ref<HTMLElement | null>(null);

// 计算是否显示箭头按钮
const showLeftArrow = computed(() => {
  if (!historyScrollRef.value) return false;
  return historyScrollRef.value.scrollLeft > 0;
});

const showRightArrow = computed(() => {
  if (!historyScrollRef.value) return false;
  const { scrollLeft, scrollWidth, clientWidth } = historyScrollRef.value;
  return scrollWidth > clientWidth && scrollLeft < scrollWidth - clientWidth - 5;
});

// 滚动到最左侧
const scrollToLeft = () => {
  if (historyScrollRef.value) {
    historyScrollRef.value.scrollTo({ left: 0, behavior: 'smooth' });
  }
};

// 滚动到最右侧
const scrollToRight = () => {
  if (historyScrollRef.value) {
    const maxScroll = historyScrollRef.value.scrollWidth - historyScrollRef.value.clientWidth;
    historyScrollRef.value.scrollTo({ left: maxScroll, behavior: 'smooth' });
  }
};

// 更新箭头按钮状态
const updateArrowVisibility = () => {
  nextTick(() => {
    // 强制触发computed重新计算
    if (historyScrollRef.value) {
      const event = new Event('scroll');
      historyScrollRef.value.dispatchEvent(event);
    }
  });
};

// 添加滚动事件监听
const handleScroll = () => {
  // 触发computed重新计算箭头状态
};

// 处理鼠标滚轮事件
const handleWheel = (event: WheelEvent) => {
  if (historyScrollRef.value) {
    event.preventDefault();
    // 增加滚动灵敏度，使用deltaY的2倍来更好地控制
    const scrollAmount = event.deltaY * 2;
    historyScrollRef.value.scrollLeft += scrollAmount;
  }
};

onMounted(() => {
  if (historyScrollRef.value) {
    historyScrollRef.value.addEventListener('scroll', handleScroll);
    historyScrollRef.value.addEventListener('wheel', handleWheel);
    updateArrowVisibility();
  }
});

onUnmounted(() => {
  if (historyScrollRef.value) {
    historyScrollRef.value.removeEventListener('scroll', handleScroll);
    historyScrollRef.value.removeEventListener('wheel', handleWheel);
  }
});

// 监听图片数量变化
watch(generatedImages, () => {
  nextTick(() => {
    updateArrowVisibility();
  });
}, { deep: true });

// 显示指定的历史图片
const showImage = (index: number) => {
  activeImageIndex.value = index;
};

// 生成图片函数
const handleGenerateImage = async () => {
  if (!message.value.trim()) {
    alert('请输入提示词');
    return;
  }

  isGenerating.value = true;

  try {
    // 准备请求数据
    const requestData = {
      modelId: currentModel.value,  // 修改为modelId，与后端接口一致
      message: message.value,
      weight: weight.value,
      num: generationCount.value,
      width: imageWidth.value,
      height: imageHeight.value
    };
    


    console.log('请求参数:', requestData);

    // 调用V2 API生成图片
    const response = await apiConfig.getAxiosInstance().post('/image/v2', requestData);

    // 处理响应
    if (response && response.data && response.data.code === 0 && response.data.data && response.data.data.length > 0) {
      // 将新图片添加到历史记录左侧
      const newImages = response.data.data.map((img: string, index: number) => ({
        url: img,
        name: `生成图片 ${new Date().toLocaleString()} ${index > 0 ? `(${index + 1})` : ''}`
      }));
      
      // 在数组开头添加新图片（最新的在左侧）
      generatedImages.value.unshift(...newImages.reverse());
      
      // 始终显示第一张图片（最新的第一张）
      activeImageIndex.value = 0;
      
      // 更新箭头按钮状态
      nextTick(() => {
        updateArrowVisibility();
      });
    } else {
      alert('生成图片失败: ' + (response?.data?.message || response?.data?.msg || '未知错误'));
    }
  } catch (error) {
    console.error('生成图片时出错:', error);
    alert('生成图片时出错: ' + (error instanceof Error ? error.message : String(error)));
  } finally {
    isGenerating.value = false;
  }
};
</script>

<style src="../../../assets/css/ImageGeneration.css" scoped></style>